import os
import pandas as pd

from service.stock.account import ProfitLossRecord
from utils.util import FlaskTool


class SellingPoint:
    def __init__(self, profit_loss_per=2, loss_per=2):
        self.profit_loss_per = profit_loss_per  # 盈亏比2：1
        self.loss_per = loss_per  # 跌2%就卖

    def commomnProfitLoss(self, buy_price, now_price):
        '''
        普通盈亏比
        '''
        # 止损点
        stop_losss_point = buy_price * (1 - self.loss_per / 100)
        # 止盈点
        stop_profit_point = buy_price * (1 + self.loss_per * 2 / 100)
        if now_price <= stop_losss_point:
            return True, now_price
        if now_price >= stop_profit_point:
            return True, now_price
        return False, now_price

    def dynamicProfitLoss(self, pd_data):
        '''
        动态盈亏比设定，盈利不封顶，止损点随涨幅上移（止损百分比不变|止损百分比阶梯调整）
        需要的参数：now_price,buy_price,loss_point,hith_point,base_point=buy_price=now_price
        1. now_price<=loss_point sell
        2. loss_point<now_price<buy_price   loss_point不变,base_price=buy_price
        3. buy_price<now_price<high_point  base_price=now_price,loss_point=base_price*(1+8%)
        4. now_price>high_point    变动盈亏比率
        :param profitLossRecord: service.stock.account.ProfitLossRecord
        :return: 买卖信号
        '''
        buy_price = pd_data['buy_price'].iat[-1]
        now_price = pd_data['now_price'].iat[-1]
        loss_ratio = pd_data['loss_ratio'].iat[-1]
        profit_ratio = pd_data['profit_ratio'].iat[-1]
        # 最高价处理
        high_price = pd_data['high_price'].max()

        stop_profit_point = pd_data['stop_profit_point'].iat[-1]
        if not stop_profit_point:
            stop_profit_point = buy_price * (1 + profit_ratio / 100)

        stop_losss_point = pd_data['stop_losss_point'].iat[-1]

        if not stop_losss_point:
            stop_losss_point = buy_price * (1 + loss_ratio / 100)

        if now_price > stop_losss_point and high_price <= buy_price:
            base_price = buy_price
            pd_data['base_price'] = base_price
            pd_data['stop_losss_point'] = stop_losss_point
            pd_data['stop_profit_point'] = stop_profit_point

        elif high_price > buy_price and high_price < stop_profit_point:
            base_price = high_price
            stop_losss_point = base_price * (1 + loss_ratio / 100)
            pd_data['base_price'] = base_price
            pd_data['stop_losss_point'] = stop_losss_point
            pd_data['stop_profit_point'] = stop_profit_point

        if now_price <= stop_losss_point:
            # sell
            return True
        return False
        # elif self.now_price > stop_profit_point:


if __name__ == '__main__':
    # abspath = os.path.dirname(__file__)
    # # 拼接加载路径
    # datapath = os.path.join(abspath, 'stock_sh.601899_data.csv')
    # pd_read_csv = pd.read_csv(datapath, index_col='date', usecols=[0,2, 3, 4, 5, 7, 12])
    # pd_read_csv.columns

    '''
    self.buy_price = None
        self.now_price = None
        self.base_price = None
        self.loss_point = None
        self.profit_point = None
        self.create_time = None

    '''
    list = []
    record = ProfitLossRecord()
    setattr(record, 'buy_price', 9.42)
    setattr(record, 'now_price', 9.42)
    setattr(record, 'high_price', 9.49)
    setattr(record, 'create_time', '2021-01-14 10:00:00')

    record1 = ProfitLossRecord()
    setattr(record1, 'buy_price', 9.42)
    setattr(record1, 'now_price', 9.25)
    setattr(record1, 'high_price', 9.65)
    setattr(record1, 'create_time', '2021-01-14 10:00:00')
    list.append(record)
    list.append(record1)
    model_list = FlaskTool.modelList(list)
    pd_data = pd.DataFrame.from_records(model_list,exclude=['position_id'])
    sign = SellingPoint().dynamicProfitLoss(pd_data)
    print(pd_data)
